﻿using System.Dynamic;
using Basic.FormCollect;
using Basic.FormRemoteModel.PageCalculate.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.Model;
using Basic.UserFormService.Page.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace Basic.UserFormService.Page
{
    internal class DataTableCalculate : IDataTableCalculate
    {
        private readonly IPageDataTableService _DataTable;
        private readonly IAgentFormCollect _AgentForm;
        private readonly IPhysicsQueryFillService _FillRow;

        public DataTableCalculate ( IPageDataTableService table,
            IAgentFormCollect agentForm,
            IPhysicsQueryFillService fillRow )
        {
            this._DataTable = table;
            this._AgentForm = agentForm;
            this._FillRow = fillRow;
        }

        public DataTableResult Query ( CalculateArg arg, IBasicPage paging )
        {
            DataTableBody body = this._DataTable.Get(arg.Id, arg.CompanyId, arg.Extend);
            if ( body.Query == null )
            {
                return null;
            }
            QueryStruct query;
            if ( !arg.Search.IsNull() )
            {
                IWhereCol[] where = arg.Search.GetWhere(body.Cols);
                query = body.Query.Clone();
                query.Where = query.Where.Merge(where);
            }
            else
            {
                query = body.Query;
            }

            ExpandoObject[] rows = this._AgentForm.Query(query, paging, out int count);
            if ( rows.IsNull() )
            {
                return null;
            }
            DataTableResult result = new DataTableResult();
            result.Rows = rows;
            if ( !body.ExtendCol.IsNull() )
            {
                this._FillRow.InitRows(rows, body.ExtendCol);
            }
            result.Count = count;
            return result;
        }
    }
}
